package com.dq.service.order.impl;

import com.dq.exception.customException.AdminException;
import com.dq.controller.in.orders.CusSaleQuery;
import com.dq.controller.in.orders.UserOrderQuery;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.domain.orders.UserOrder;
import com.dq.domain.sys.user.center.UserAccountStaffUser;
import com.dq.domain.org.Org;
import com.dq.repository.BaseRepositories;
import com.dq.service.order.CusSaleService;
import com.dq.service.org.OrgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuhui
 * @date 2019/11/25 0025 11:37:03
 */
@Service
public class CusSaleServiceImpl extends BaseRepositories implements CusSaleService {

    @Autowired
    private OrgService orgService;
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 根据中间表获取 销售单列表
     * @param userOrderQuery
     * @param deleted
     * @return
     * @throws AdminException
     */
    @Override
    public List<UserAccountStaffUser> userOrderList(UserOrderQuery userOrderQuery, Boolean deleted) throws AdminException {
        StringBuilder sql = new StringBuilder();
        sql.append("select u from UserAccountStaffUser u ");
        sql = getOrgListHql(sql, userOrderQuery, deleted);

        // 设置动态参数
        Map<String, Object> query = new HashMap<>(16);
        if(userOrderQuery.getPage() != null && userOrderQuery.getSize() != null) {
            query.put("size", userOrderQuery.getSize());
            query.put("page", userOrderQuery.getPage());
        }
        List<UserAccountStaffUser> list = dao.find(sql.toString(), query);

        return list;
    }
    @Override
    public Long userOrderCount(UserOrderQuery userOrderQuery, Boolean deleted) throws AdminException {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT u from UserAccountStaffUser u ");
        sql = getOrgListHql(sql, userOrderQuery, deleted);

        System.out.println(sql.toString());


        List<Object> list = dao.find(sql.toString(), new HashMap<>(16));
        Long count = Long.parseLong(String.valueOf(list.size()));

        return count;
    }

    /**
     * 查询列表 条件
     * @param userOrderQuery
     * @return
     * @throws AdminException
     */
    public StringBuilder getOrgListHql(StringBuilder sql, UserOrderQuery userOrderQuery, Boolean deleted) throws AdminException {
        if(deleted == null) {
            deleted = false;
        }

        sql.append(" where u.deleted = ").append(deleted);

        if(userOrderQuery.getOrgId() != null) {
            sql.append(" and u.userOrder.org.id = ").append(userOrderQuery.getOrgId());
        }else {
            // 只显示负责门店信息
            String orgIdsIn = orgService.getIdListAllByUser();
            if(StringUtils.isNotBlank(orgIdsIn)) {
                sql.append(" and u.userOrder.org.id in ").append(orgIdsIn);
            }
        }

        if(userOrderQuery.getWxUserId() != null) {
            sql.append(" and u.userOrder.wxUser.id = ").append(userOrderQuery.getWxUserId());
        }
        if(StringUtils.isNotBlank(userOrderQuery.getWxUserRealcName())) {
            sql.append(" and u.userOrder.wxUser.userRealcName like '").append(BaseAdminQuery.likeSql(userOrderQuery.getWxUserRealcName())).append("'");
        }
        if(userOrderQuery.getSellStaffUserId() != null) {
            sql.append(" and u.staffUser.id = ").append(userOrderQuery.getSellStaffUserId());
        }
        if(StringUtils.isNotBlank(userOrderQuery.getSellStaffUserName())) {
            sql.append(" and u.staffUser.userRealcName like '").append(BaseAdminQuery.likeSql(userOrderQuery.getSellStaffUserName())).append("'");
        }
        if(StringUtils.isNotBlank(userOrderQuery.getOrgName())) {
            sql.append(" and u.userOrder.org.name like '").append(BaseAdminQuery.likeSql(userOrderQuery.getOrgName())).append("'");
        }
        if(StringUtils.isNotBlank(userOrderQuery.getOrdersNo())) {
            sql.append(" and u.userOrder.ordersNo = '").append(userOrderQuery.getOrdersNo()).append("'");
        }
        if(userOrderQuery.getOrderSource() != null) {
            sql.append(" and u.userOrder.orderSource = ").append(userOrderQuery.getOrderSource().ordinal());
        }
        if(userOrderQuery.getStatus() != null) {
            sql.append(" and u.userOrder.status = ").append(userOrderQuery.getStatus().ordinal());
        }
        if(userOrderQuery.getPayType() != null) {
            sql.append(" and u.userOrder.payType = ").append(userOrderQuery.getPayType().ordinal());
        }
        if(userOrderQuery.getIsOwed() != null) {
            sql.append(" and u.userOrder.isOwed = ").append(userOrderQuery.getIsOwed());
        }
        if(userOrderQuery.getTimeBegin() != null) {
            sql.append(" and u.userOrder.createTime >= ").append(userOrderQuery.getTimeBegin());
        }
        if(userOrderQuery.getTimeEnd() != null) {
            sql.append(" and u.userOrder.createTime <= ").append(userOrderQuery.getTimeEnd());
        }
        if(userOrderQuery.getPriceBegin() != null) {
            sql.append(" and u.userOrder.price >= ").append(userOrderQuery.getPriceBegin());
        }
        if(userOrderQuery.getPriceEnd() != null) {
            sql.append(" and u.userOrder.price <= ").append(userOrderQuery.getPriceEnd());
        }

        if(StringUtils.isNotBlank(userOrderQuery.getSearchBox())) {
            sql.append(" and ( u.userOrder.wxUser.userRealcName like '").append(BaseAdminQuery.likeSql(userOrderQuery.getSearchBox())).append("'");
            sql.append(" or u.userOrder.ordersNo = ").append(userOrderQuery.getSearchBox());
            sql.append(" or u.userOrder.wxUser.username like '").append(BaseAdminQuery.likeSql(userOrderQuery.getSearchBox())).append("' ) ");
        }

        sql.append(" GROUP BY u.userOrder.id");
        sql.append(" order BY u.userOrder.createTime desc");
        return sql;
    }

    @Override
    public List<UserOrder> findByWhere(CusSaleQuery cusSaleQuery)throws AdminException{
        StringBuilder hql = new StringBuilder("select u from UserOrder u where u.deleted=false");
        Query q = createWhereHql(cusSaleQuery,hql);
        q.setFirstResult((cusSaleQuery.getPage()-1)*cusSaleQuery.getSize());
        q.setMaxResults(cusSaleQuery.getSize());
        List<UserOrder> userOrderList = q.getResultList();
        return userOrderList;
    }

    @Override
    public Long countByWhere(CusSaleQuery cusSaleQuery)throws AdminException{
        StringBuilder hql = new StringBuilder("select count(u) from UserOrder u where u.deleted=false");
        Query q = createWhereHql(cusSaleQuery,hql);
        return new Long((long) q.getResultList().get(0));
    }

    @Override
    public List<UserOrder> findAllUserOrderList(UserOrderQuery userOrderQuery) throws AdminException {

        return null;
    }

    public Query createWhereHql(CusSaleQuery cusSaleQuery,StringBuilder hql){
        if(null!=cusSaleQuery.getId()){
            hql.append(" and u.wxUser.id=:wxUser");
        }
        if(StringUtils.isNotEmpty(cusSaleQuery.getSaleNo())){
            hql.append(" and u.ordersNo like:ordersNo");
        }
        if(null!=cusSaleQuery.getBeginTime()){
            hql.append(" and u.createTime >=:beginTime");
        }
        if(null!=cusSaleQuery.getEndTime()){
            hql.append(" and u.createTime <=:endTime");
        }
        if(null!=cusSaleQuery.getOrderSource()){
            hql.append(" and u.orderSource =:orderSource");
        }
        if(null!=cusSaleQuery.getStatus()){
            hql.append(" and u.status =:status");
        }
        if(null!=cusSaleQuery.getPayType()){
            hql.append(" and u.payType =:payType");
        }
        if(null!=cusSaleQuery.getIsOwed() && cusSaleQuery.getIsOwed()){
            hql.append(" and u.isOwed =:isOwed");
        }
        if(null!=cusSaleQuery.getStaffUserId()){
            hql.append(" and u.wxUser.staffUser.id =:staffUser");
        }
        if(null!=cusSaleQuery.getOrgId()){
            hql.append(" and u.org=:org");
        }
        if(StringUtils.isNotEmpty(cusSaleQuery.getValue())){
            hql.append(" and (u.wxUser.cardNo like:value");
            hql.append(" or u.wxUser.username like:value");
            hql.append(" or u.wxUser.userRealcName like:value)");
        }
        if(StringUtils.isNotEmpty(cusSaleQuery.getOrgName())){
            hql.append(" and u.org.name=:orgName");
        }
         hql.append(" order by id desc");
        Query query = entityManager.createQuery(hql.toString());
        if(null!=cusSaleQuery.getId()){
            query.setParameter("wxUser",cusSaleQuery.getId());
        }
        if(StringUtils.isNotEmpty(cusSaleQuery.getSaleNo())){
            query.setParameter("ordersNo","%"+cusSaleQuery.getSaleNo()+"%");
        }
        if(null!=cusSaleQuery.getBeginTime()){
            query.setParameter("beginTime",cusSaleQuery.getBeginTime());
        }
        if(null!=cusSaleQuery.getEndTime()){
            query.setParameter("endTime",cusSaleQuery.getEndTime());
        }
        if(null!=cusSaleQuery.getOrderSource()){
            query.setParameter("orderSource",cusSaleQuery.getOrderSource());
        }
        if(null!=cusSaleQuery.getStatus()){
            query.setParameter("status",cusSaleQuery.getStatus());
        }
        if(null!=cusSaleQuery.getPayType()){
            query.setParameter("payType",cusSaleQuery.getPayType());
        }
        if(null!=cusSaleQuery.getIsOwed() && cusSaleQuery.getIsOwed()){
            query.setParameter("isOwed",cusSaleQuery.getIsOwed());
        }
        if(null!=cusSaleQuery.getStaffUserId()){
            query.setParameter("staffUser",cusSaleQuery.getStaffUserId());
        }
        if(null!=cusSaleQuery.getOrgId()){
            Org org = dao.get(Org.class,cusSaleQuery.getOrgId());
            query.setParameter("org",org);
        }
        if(StringUtils.isNotEmpty(cusSaleQuery.getValue())){
            query.setParameter("value","%"+cusSaleQuery.getValue()+"%");
        }
        if(StringUtils.isNotEmpty(cusSaleQuery.getOrgName())){
            query.setParameter("orgName",cusSaleQuery.getOrgName());
        }
        return query;
    }
}
